/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controllers;

import Controllers.utils.HibernateUtil;
import Controllers.utils.URLUtils;
import DAO.CategProdManager;
import DAO.ProductsManager;
import Model.CategProd;
import Model.Produit;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Anthares
 */
public class Shop extends BaseServlet {
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request  servlet request
     * @param response servlet response
     * <p/>
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException      if an I/O error occurs
     */
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String locale = getLocaleString(request);
        
        HashMap<String, String> requestedRessource = URLUtils.getRequestedRessource(getServletContext(), request);

        String action = requestedRessource.get("action");
        List<CategProd> catList = new CategProdManager(HibernateUtil.getSessionFactory(), locale).getAllCategProd();
        request.setAttribute("categoryList", catList);
        List<Produit> prodList=null;
        
        String paramCateg = request.getParameter("category");
        
        if(action == null || paramCateg.equals("0")){
            prodList = new ProductsManager(HibernateUtil.getSessionFactory(), locale).getAllProducts();
        } else {
            if(action.equals("categ")){
                prodList = new ProductsManager(HibernateUtil.getSessionFactory(), locale).getAllProductByCategory(Integer.parseInt(paramCateg));
            } else {
                request.setAttribute("errorCode", 404);
                request.getRequestDispatcher("/error.jsp").forward(request, response);
            }
        }
        request.setAttribute("productList", prodList);
        request.getRequestDispatcher("/shop.jsp").forward(request, response);
    }
}
